package com.zhanghp.class036;

import com.zhanghp.common.TreeNode;

/**
 * 二叉树先序序列化和反序列化<br/>
 * 测试链接 : https://leetcode.cn/problems/serialize-and-deserialize-binary-tree/
 *
 * @author zhanghp
 * @since 2024/4/18 11:07
 */
public class Code05_PreorderSerializeAndDeserialize {


    static class Codec {

        // Encodes a tree to a single string.
        public String serialize(TreeNode root) {
            StringBuilder sb = new StringBuilder();
            f(root, sb);
            return sb.toString();
        }

        public void f(TreeNode root, StringBuilder builder) {
            if (root == null) {
                builder.append("#,");
                return;
            }
            builder.append(root.val + ",");
            f(root.left, builder);
            f(root.right, builder);
        }


        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            cnt = 0;
            String[] split = data.split(",");
            return f(split);
        }



        public int cnt;

        public TreeNode f( String[] vals){
            String val = vals[cnt++];
            if (val.compareTo("#") == 0) {
                return null;
            }
            TreeNode node = new TreeNode(Integer.parseInt(val));
            node.left = f(vals);
            node.right= f(vals);
            return node;

        }
    }

}
